package com.alibaba.citrus.cr.mn.order.center.facade.adapter.impl;

import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.BcLinkAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ForecastClosedToSAPRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ForecastClosedToSAPRequest.Items;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.SendMsgService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.impl.SendMsgServiceImpl;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.mnordercenter.model.dto.Modifiers;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BcLinkAdapterImpl implements BcLinkAdapter {

    private static final Log log = Log.getLogger(SendMsgServiceImpl.class);

    @Resource
    private SendMsgService sendMsgService;

    @Override
    public void forecastClosedToSap(Map<ForecastOrderSDO, List<ForecastOrderLineSDO>> sapParamMap) {
        log.info("BcLinkAdapterImpl#forecastClosedToSap sapParamMap:{}", JSON.toJSONString(sapParamMap));
        if (sapParamMap.isEmpty()) {
            return;
        }
        sapParamMap.forEach((key, value) -> {
            ForecastClosedToSAPRequest forecastClosedToSAPRequest = ForecastClosedToSAPRequest.builder()
                    .VBELN(key.getOuterOrderId())
                    .modifier(key.getModifierCode())
                    .modifyTime(DateUtils.toDateStr(new Date(), DateUtils.DATETIME_FORMAT))
                    .build();
            List<Items> items = new ArrayList<>();
            value.forEach(orderLine -> {
                items.add(Items.builder()
                        .POSNR(orderLine.getOuterLineId())
                        .ABGRU(orderLine.getRefuseReasonCode())
                        .build());
            });
            forecastClosedToSAPRequest.setItems(items);
            String message = JSON.toJSONString(forecastClosedToSAPRequest);
            log.info("BcLinkAdapterImpl#forecastClosedToSap forecastClosedToSAPRequest:{}", message);
            sendMsgService.sendForecastClosedMsgToSAP(message);
        });
    }
}
